﻿
using System;
using System.Text;

namespace NMbsDuplex.Consolet
{
    using System.Net;
    using System.Net.Sockets;
    using NMbsDuplex.ProtocalBuffer.Bifrost;
    using TCPServerX.Deamon;
    using MrPoetic.MatLab.Algebra;

    class Program
    {
        // TCP解包的缓冲器大小
        const int CacheSiz = 1024;
        const string cmd = "[FILE]";

        static internal void TestingSockPIPETransFile()
        {
            System.Threading.Thread.Sleep(1234);
            LambdaUtil.Show8Bit(120);

            // 模拟 Sock 收什么就回显什么 注意传输码是 UTF8
            var Listener = new Socket(
                AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp
            );

            Listener.Connect(new IPEndPoint(IPAddress.Loopback, 33036));
            if (Listener.Connected)
            {
                Action UP1ts = () => {
                    byte[] x1 = new byte[CacheSiz];
                    int c2 = Listener.Receive(x1);
                    Console.WriteLine(Encoding.UTF8.GetString(x1, 0, c2));
                };
                UP1ts();

                string lines = string.Empty;
                while ((lines = Console.ReadLine()) != null)
                {
                    Console.WriteLine("请输入指令集");
                    if (string.IsNullOrWhiteSpace(lines))
                    {
                        Listener.Send(Encoding.UTF8.GetBytes(cmd));
                    }
                    else
                    {
                        byte[] blines = Encoding.UTF8.GetBytes(lines);
                        Listener.Send(blines);
                    }

                    if (lines.Contains("[FILE]|"))
                    {
                        var pageInfo = Listener.TCPUnPacking1st();
                        Listener.TCPUnPackingContinuously(pageInfo.Item1, pageInfo.Item2);
                    }
                    else
                    {
                        int N = 0;
                        string msg = TCPExtension.QosRecv(Listener, ref N);
                        Console.WriteLine(msg);
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            TestingSockPIPETransFile();
        }
    }
}
